#!/usr/bin/env python
#################################################################################
#   Copyright (C) 2007 Daniel Kersten / Tim Kersten                             #
#   (See the file AUTHORS for details.)                                         #
#                                                                               #
#   Nexus-Ed is free software; you can redistribute it and/or modify            #
#   it under the terms of the GNU General Public License as published by        #
#   the Free Software Foundation; either version 2 of the License, or           #
#   (at your option) any later version.                                         #
#                                                                               #
#   Nexus-Ed is distributed in the hope that it will be useful,                 #
#   but WITHOUT ANY WARRANTY; without even the implied warranty of              #
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the                #
#   GNU General Public License for more details.                                #
#                                                                               #
#   You should have received a copy of the GNU General Public License           #
#   along with Nexus-Ed; if not, write to the Free Software                     #
#   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA    #
#   or visit http://www.gnu.org/licenses/gpl.txt                                #
#                                                                               #
#################################################################################


# Nexus Server Program

from twisted.internet import protocol, reactor

PORT = 11018

class NexusServer:
	'''
	The nexus server.
	'''
	def __init__(self):
		pass

nexusServer = NexusServer()


class NexusServerProtocol(protocol.Protocol):

	nexusServer.nexusfile = ""
	
	def connectionMade(self):
		clnt = self.clnt = self.transport.getPeer().host
		print '...connected from:', clnt
		
	def dataReceived(self, data):
		m = match('^[0-9]+[id]', data);
		if m is not None:
			m = m.group()
			textData = data[len(m)+1:]
			position = m[:-1]
			command = m[-1]
			
			if command is "i":
				self.insertText(position, textData)
				self.sendStatus('OK')
			elif command is "d":
				self.deleteText(position, textData)
				self.sendStatus('OK')
			else:
				self.sendStatus('ERROR')
				
		print 'file:\n' + self.nexusfile
	
	def insertText(self, position, text):
		file = nexusServer.nexusfile
		nexusServer.nexusfile = file[0:position] + text + file[position:]
		
	
	def deleteText(self, position, amountToDelete):
		file = nexusServer.nexusfile
		nexusServer.nexusfile = file[0:position] + file[position + amountToDelete:]

factory = protocol.Factory()
factory.protocol = NexusServerProtocol

print 'waiting for connection...'

reactor.listenTCP(PORT, factory)
reactor.run()


"""
from socket import *
from time import ctime

HOST = ''                                              # Host is left blank to allow bind() to use any available address
PORT = 11018
BUFSIZ = 1024                                          # Buffer size in kb
MAXCON = 5                                             # Maximum connectins server will accept simultaineously
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INIT, SOCK_STREAM)              # create server socket
tcpSerSock.bind(ADDR)                                  # bind socket to address
tcpSerSock.listen(MAXCON)                              # listen for connections 
while True:                                            # create infinite loop
	print 'waiting for connection...'
	tcpCliSock, addr = tcpSerSock.accept()             # accept client connections
	print '...connected from:', addr
	
	while True:                                        # communication loop
		data = tcpCliSock.recv(1024)                   # server/client dialog (receive)
		if not data:                                   # if the client's message is blank, quit
			break
		tcpCliSock.send('[%s] %s' % (ctime(), data))   # server/client dialog (send)
	
	tcpCliSock.close()                                 # close client socket

tcpSerSock.close()                                     # close server socket
"""

